package com.example.base.ext.tab_expand.tab

import android.util.Log
import android.widget.LinearLayout
import android.widget.TextView
import com.example.base.ext.tab_expand.indicator.BaseIndicator
import com.example.base.ext.tab_expand.text.BaseText
import com.google.android.material.tabs.TabLayout
import java.lang.reflect.Field

/**
 * 绑定tabLayout指示器
 */
inline fun <reified T : BaseIndicator> TabLayout.buildIndicator(): T {
    val indicator = T::class.java.newInstance()
    indicator.bindTabLayout(this)
    return indicator
}

/**
 * 绑定tabLayout文字设置
 */
inline fun <reified T : BaseText> TabLayout.buildText(): T {
    val text = T::class.java.newInstance()
    text.bindTabLayout(this)
    return text
}


fun TabLayout.fixTabItem(paddingValue :Int) {

    post(Runnable {
        // 拿到tabLayout的slidingTabIndicator属性
        try {
            val slidingTabIndicatorField: Field =
                javaClass.getDeclaredField("slidingTabIndicator")
            slidingTabIndicatorField.isAccessible = true
            val mTabStrip = slidingTabIndicatorField[this] as LinearLayout
            Log.i("tabLayout", mTabStrip.childCount.toString() + "   --")
            for (i in 0 until mTabStrip.childCount) {
                val tabView = mTabStrip.getChildAt(i)
                //                        拿到tabview的textview属性
                val textViewField = tabView.javaClass.getDeclaredField("textView")
                textViewField.isAccessible = true
                val mTextView = textViewField[tabView] as TextView
                tabView.setPadding(0, 0, 0, 0)

                var width: Int = mTextView.getWidth()
                if (width == 0) {
                    mTextView.measure(0, 0);
                    width = mTextView.getMeasuredWidth();
                }
//                        控制Item条目的宽度，这种设置的话就是等分
                val layoutParams = tabView.layoutParams as LinearLayout.LayoutParams
                layoutParams.width = width + paddingValue
                //  layoutParams.weight = 1f
                tabView.layoutParams = layoutParams
                tabView.invalidate()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    })


}





